package dao

import (
	"context"
	"gitee.com/hxchjm/go-admin/internal/models"
	"gitee.com/hxchjm/go-admin/pkg/db"
	"gitee.com/hxchjm/go-admin/pkg/jwtauth"
	"github.com/hxchjm/log"
	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type SysPost struct {
	models.SysPost
}

//func (*SysPost) TableName() string {
//	return "sys_post"
//	//return fmt.Sprintf("%s.sys_post", db.GetDBName())
//}

// GetPage 获取SysPost列表
func (e SysPost) GetPage(ctx context.Context, req *models.ReqPostPage) (list []SysPost, count int64, err error) {
	if req.Size <= 0 {
		req.Size = 20
	}
	err = db.GetDB().WithContext(ctx).Model(e).Debug().
		Where(e).
		Limit(req.Size).Offset((req.Page - 1) * req.Size).Find(&list).
		Count(&count).Error
	if err != nil {
		log.Errorf(ctx, "db error:%s", err)
		return
	}
	return
}

// Get 获取SysPost对象
func (e SysPost) Get(ctx context.Context) (*SysPost, error) {
	var data SysPost
	if err := db.GetDB().WithContext(ctx).Model(&data).First(&data, e.PostId).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			err = errors.New("查看对象不存在或无权查看")
		}
		return nil, err
	}
	return &data, nil
}

// Insert 创建SysPost对象
func (e *SysPost) Insert(ctx context.Context) error {
	if err := db.GetDB().Create(&e).Error; err != nil {
		log.Errorf(ctx, "db error:%s", err)
		return err
	}
	return nil
}

// Update 修改SysPost对象
func (e *SysPost) Update(ctx context.Context) error {
	var err error
	var model = SysPost{}
	tx := db.GetDB().WithContext(ctx).First(&model, e.PostId)
	cTime := model.CreatedAt
	_ = copier.CopyWithOption(&model, e, copier.Option{IgnoreEmpty: true})
	model.CreatedAt = cTime
	model.UpdateBy = jwtauth.GetClaims(ctx).UID
	tx = tx.Save(&model)
	if err = tx.Error; err != nil {
		log.Errorf(ctx, "db error:%s", err)
		return err
	}
	if tx.RowsAffected == 0 {
		return errors.New("无权更新该数据")

	}
	return nil
}

// Delete 删除SysPost
func (e SysPost) Delete(ctx context.Context) error {
	var err error

	tx := db.GetDB().WithContext(ctx).Model(&e).Delete(&e, e.PostId)
	if err = tx.Error; err != nil {
		log.Errorf(ctx, "Delete error: %s", err)
		return err
	}
	if tx.RowsAffected == 0 {
		err = errors.New("无权删除该数据")
		return err
	}
	return nil
}
